import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;


class Messages{
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Messages{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}
@WebServlet("/practices")
public class Practice extends HttpServlet {
    ObjectMapper mapper=new ObjectMapper();
    List<Messages> list=new LinkedList<>();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        Messages messages=mapper.readValue(req.getInputStream(),Messages.class);
        System.out.println("收到的数据是："+messages);
        list.add(messages);

        String respJson=mapper.writeValueAsString(messages);
        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(respJson);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");

        String respJson=mapper.writeValueAsString(list);
        System.out.println("获取的数据是："+respJson.toString());
        resp.getWriter().write(respJson);
    }
}
